import torch
import torch.nn as nn
from torchvision.models.resnet import Bottleneck

class ResNet50(nn.Module):
    def __init__(self, num_classes=1000):
        super(ResNet50, self).__init__()
        # 初始卷积层和池化层
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        self.inplanes = 64

        # ResNet的4个stage，每个stage包含多个Bottleneck块
        self.layer1 = self._make_layer(64, 3)
        self.layer2 = self._make_layer(128, 4, stride=2)
        self.layer3 = self._make_layer(256, 6, stride=2)
        self.layer4 = self._make_layer(512, 3, stride=2)

        # 全局平均池化和分类器
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(512 * 4, num_classes)

        # 初始化权重
        self._initialize_weights()

    def _make_layer(self, planes, blocks, stride=1):
        layers = []
        # 第一个block可能需要downsample
        downsample = None
        if stride != 1 or self.inplanes != planes * 4:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * 4, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * 4),
            )

        layers.append(Bottleneck(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * 4
        for _ in range(1, blocks):
            layers.append(Bottleneck(self.inplanes, planes))

        return nn.Sequential(*layers)

    def _initialize_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def forward(self, x):
        # 支持Layer Range Deduction的前向传播
        features = {}
        
        # Stage 0: 初始层
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)
        features['stage0'] = x

        # Stage 1-4: ResNet主体
        x = self.layer1(x)
        features['stage1'] = x
        x = self.layer2(x)
        features['stage2'] = x
        x = self.layer3(x)
        features['stage3'] = x
        x = self.layer4(x)
        features['stage4'] = x

        # 分类器
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)
        features['output'] = x

        return x, features

    def load_pretrained_weights(self, weights_path):
        """加载预训练权重"""
        state_dict = torch.load(weights_path)
        self.load_state_dict(state_dict)

    def get_layer_range(self, start_layer, end_layer):
        """获取指定层范围的子网络，用于Layer Range Deduction"""
        layers = {
            'stage0': [self.conv1, self.bn1, self.relu, self.maxpool],
            'stage1': [self.layer1],
            'stage2': [self.layer2],
            'stage3': [self.layer3],
            'stage4': [self.layer4],
            'output': [self.avgpool, self.fc]
        }
        
        selected_layers = []
        start_found = False
        
        for stage, stage_layers in layers.items():
            if stage == start_layer:
                start_found = True
            if start_found:
                selected_layers.extend(stage_layers)
            if stage == end_layer:
                break
                
        return nn.Sequential(*selected_layers)